import gradio as gr
import requests


def ask_deepseek(api_key, question):
    # DeepSeek API 配置（请根据实际文档调整参数）
    url = "https://api.deepseek.com/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    # 构造请求数据（请根据实际 API 文档调整参数）
    data = {
        "model": "deepseek-chat",  # 根据可用模型调整
        "messages": [{"role": "user", "content": question}],
        "temperature": 0.7,
        "max_tokens": 1024
    }

    try:
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()  # 检查 HTTP 错误

        result = response.json()
        return result['choices'][0]['message']['content']
    except requests.exceptions.RequestException as e:
        return f"请求错误：{str(e)}"
    except KeyError:
        return "无法解析 API 响应"
    except Exception as e:
        return f"发生错误：{str(e)}"


# 创建 Gradio 界面
interface = gr.Interface(
    fn=ask_deepseek,
    inputs=[
        gr.Textbox(label="API Key", type="password"),
        gr.Textbox(label="输入问题", lines=3)
    ],
    outputs=gr.Textbox(label="回答", lines=10),
    title="DeepSeek 问答助手",
    description="输入您的 API Key 和问题以获取回答",
    allow_flagging="never"
)

# 启动应用
if __name__ == "__main__":
    interface.launch()